package com.qf.openapi.web.master.filter;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.*;

@WebFilter("/*")
@Slf4j
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.debug(" ================= MyFilter init =================");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        final HttpServletRequest req = (HttpServletRequest) request;

        final String requestURI = req.getRequestURI();

        log.debug("===> url={}",requestURI);

        // 把请求中的参数信息打印出来
        final Map<String, String[]> parameterMap = request.getParameterMap();
        final Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();

        final ArrayList<HashMap<String, List<String>>> params = new ArrayList<HashMap<String, List<String>>>();

        for (Map.Entry<String, String[]> entry : entries) {
            final String paramName = entry.getKey();
            final String[] paramValue = entry.getValue();
            final List<String> paramlist = Arrays.asList(paramValue);
            final HashMap<String, List<String>> map = new HashMap<>();
            map.put(paramName,paramlist);
            params.add(map);
        }

        log.debug("请求参数为,params={}",params);
        // 请求头信息打印
        final Enumeration<String> headerNames = req.getHeaderNames();

        final HashMap<String, String> headermap = new HashMap<>();
        while (headerNames.hasMoreElements()) {
            final String headname = headerNames.nextElement();
            final String headerValue = req.getHeader(headname);
            headermap.put(headname,headerValue);
        }

        log.debug("请求头信息为，headermap={}",headermap);

        // 从请求体中获取信息
//        final ServletInputStream inputStream = request.getInputStream();
//        final BufferedReader reader = request.getReader();


        final long start = System.currentTimeMillis();

        // 放行当前请求
        chain.doFilter(request,response);

        final long end = System.currentTimeMillis();

        log.debug("<=== url={},time={}",requestURI,(end-start));

    }

    @Override
    public void destroy() {
        log.debug(" ================= MyFilter destroy =================");
    }
}
